package cn.cyb.server.service;

import cn.cyb.server.common.exception.ServiceException;
import cn.cyb.server.domain.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

/**
 * @author yuebo
 * @date 2024/12/25
 */
@Component
public class SysLoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private TokenService tokenService;

    public String login(String userName, String password) {
        System.out.println("SysLoginService.login() userName=" + userName + " ,password=" + password);
        Authentication authentication = null;
        try {
            // 封装Authentication对象
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userName, password);
            // 调用authenticate进行认证，该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            throw new ServiceException(e);
        }
        // 取出认证成功后的用户信息
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成jwt
        return tokenService.createToken(loginUser);
    }
}
